﻿using Framework;
using Koala.Framework.FileSystems.App_Data;
using Koala.Framework.Update;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using IUpdateController = Koala.Extras.Update.IUpdateController;

namespace Koala.JiraTool.Update
{
    public class MainFormEvent : IMainFormEvent
    {
        private readonly IUpdateController _updateController;
        private readonly INotificationController _notificationController;
        private readonly IPluginUpdateController _pluginUpdateController;
        private readonly IAppDataFolder _appDataFolder;
        private static bool _isPluginShow;
        private static bool _isShow;

        public MainFormEvent(IUpdateController updateController, INotificationController notificationController, IPluginUpdateController pluginUpdateController, IAppDataFolder appDataFolder)
        {
            _updateController = updateController;
            _notificationController = notificationController;
            _pluginUpdateController = pluginUpdateController;
            _appDataFolder = appDataFolder;
        }

        #region Implementation of IMainFormEvent

        /// <summary>
        /// 主窗体加载完毕。
        /// </summary>
        public void LoadOk()
        {
            try
            {
                if (_appDataFolder.DirectoryExists("Temp"))
                {
                    _appDataFolder.DeleteDirectory("Temp", true);
                }
            }
            catch
            {
            }
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    if (_isShow && _isPluginShow)
                    {
                        break;
                    }
                    try
                    {
                        if (_isShow) continue;
                        if (!_updateController.CheckUpdate()) continue;
                        _isShow = true;
                        _notificationController.Message("发现主程序更新，该消息不回重复提醒。");
                        Process.Start(Path.Combine(Application.StartupPath, "Update.exe"), Application.ExecutablePath);
                    }
                    catch
                    {
                    }
                    try
                    {
                        if (_isPluginShow) continue;
                        if (!_pluginUpdateController.CheckUpdate()) continue;
                        _isPluginShow = true;
                        _notificationController.Message("发现有插件更新信息，请换到插件管理内进行更新，该消息不回重复提醒。");
                    }
                    catch
                    {
                    }
                    Thread.Sleep(new TimeSpan(0, 0, 15));
                }
            });
        }

        #endregion Implementation of IMainFormEvent
    }
}